/**
 * Created by Wenwu on 7/19/2016.
 */
define(function (require) {

    var Spinner = require('spinner');
    var spinner = new Spinner();
    var AuthDialog = require('auth_dialog');
    var authDialog = new AuthDialog();

    return function (url, params, callback, errorCallback, async) {
        var xmlhttp = null;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (xmlhttp != null) {

            var paramsInUrl = '?';
            for(var key in params){
                paramsInUrl += (key + '=' + params[key] + '&');
            }

            url += (paramsInUrl === '?' ? '' : paramsInUrl.substr(0, paramsInUrl.length - 1));

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    spinner.stop();
                    var response = JSON.parse(xmlhttp.responseText);

                    //没有认证
                    // if(response.member.sfrz==0 || response.member.sfjy==1){
                    //     console.log("ajax.js: 拦截到未认证!弹出去认证窗口！");
                    //     authDialog.show();
                    // }else{
                    //     if (xmlhttp.status == 200) {
                    //         if (typeof(callback) != 'undefined') {
                    //             callback(response);
                    //         }
                    //     } else {
                    //         if (typeof(errorCallback) != 'undefined') {
                    //             errorCallback(response);
                    //         }
                    //     }
                    // }

                    if (xmlhttp.status == 200) {
                        if (typeof(callback) != 'undefined') {
                            callback(response);
                        }
                    } else {
                        if (typeof(errorCallback) != 'undefined') {
                            errorCallback(response);
                        }
                    }

                }
            };
            spinner.start();
            xmlhttp.open('POST', url, typeof async === 'undefined');
            xmlhttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
            xmlhttp.send();
        } else {
            console.log("Your browser does not support XMLHTTP.");
        }
    }
});